/**
 * 旭日图
 * 说明：多维数据对比及下钻
data = [{
  id: 'sunburst',
  name: '漏图图',
  regioncode: "aaa",
  regionname: "aaa",
  lon: "0.92866163503169",
  lat: "30.830660058696104",
  showThumbnails:false,
  width: '300px',
  height: '300px',
  data: [{
    name: '移动端',
    children: [{
      name: '手机',
      value: 1
    }, {
      name: '平板',
      children: [{
        name: '小米',
        value: 1
      }]
    }]
  }, {
    name: 'pc端',
    value: 3,
    children: []
  }]
}]
 *
 */
import echarts from 'echarts'; // echarts 文件引入
import sgisLayerBase from '../../sgis.layer.base';
import colorPicker from './echarts.colorpicker'; // 颜色初始化配置文件
import styleModify from './echarts.stylemodify'; // 为图层设置透明度，可见性，zIndex而设置
export default {
  activeMap: {}, // 当前活动地图
  sunbrustLayer: '',
  sunbrustLayerInfo: {}, // 图层其他相关信息
  maxLevel: [], // 树的最大层级
  customSunburstColor: [],
  customSunburstLableColor: '',
  graph: [],
  // 计算data
  /**
   * @param {object} datas 数据
   * @param {number} level 层级
   * @param {number} index 第几个数据
   * 格式化初始化图标数据
   */
  calSunbrustData(datas, level, index) {
    level += 1;
    let len = 0;
    try {
      len = datas.length;
    } catch (err) {}
    if (level > this.maxLevel[index]) {
      this.maxLevel[index] = level;
    }
    for (let i = 0; i < len; i++) {
      this.curPosition += 1;
      datas[i].level = level;
      if (!datas[i].itemStyle) {
        const col = i * level + level;
        // 先进行是否存在自定义颜色行为判断 开始
        if (this.customSunburstColor.length) {
          datas[i].itemStyle = {
            color: this.randomColor(col),
            borderWidth: 0
          };
        } else {
          datas[i].itemStyle = {
            color: datas[i].itemColor ? datas[i].itemColor : this.randomColor(col),
            borderWidth: 0
          };
        }
      } else {
        const col = i * level + level;
        // 先进行是否存在自定义颜色行为判断 开始
        if (this.customSunburstColor.length) {
          datas[i].itemStyle = {
            color: this.randomColor(col),
            borderWidth: 0
          };
        } else {
          datas[i].itemStyle = {
            color: datas[i].itemColor ? datas[i].itemColor : this.randomColor(col),
            borderWidth: 0
          };
        }
      }
      if (this.customSunburstLableColor) {
        datas[i].label = {
          color: this.customSunburstLableColor
        };
      } else {
        datas[i].label = {
          color: datas[i].color ? datas[i].color : colorPicker.sunburst.color
        };
      }
      // 定义图例样式 开始
      this.graph.push({
        name: datas[i].name,
        color: datas[i].itemStyle.color
      });
      // 定义图例样式 结束
      // 先进行是否存在自定义颜色行为判断 结束
      if (datas[i].children && datas[i].children.length) {
        this.calSunbrustData(datas[i].children, level, index);
      }
    }
    return datas;
  }, // 计算数据调用
  /**
   * @param {object} datas 数据
   * @param {number} level 层级
   * @param {number} index 第几个数据
   * 格式化自定义颜色图表数据
   */
  calSunbrustDataZ(datas, level, index, layers) {
    level += 1;
    let len = 0;
    try {
      len = datas.length;
    } catch (err) {}
    if (level > this.maxLevel[index]) {
      layers.maxLevel[index] = level;
    }
    for (let i = 0; i < len; i++) {
      this.curPosition += 1;
      datas[i].level = level;
      if (!datas[i].itemStyle) {
        const col = i * level + level;
        // 先进行是否存在自定义颜色行为判断 开始
        if (layers.customSunburstColor.length) {
          datas[i].itemStyle = {
            color: layers.randomColor(col, layers, level),
            borderWidth: 0
          };
        } else {
          datas[i].itemStyle = {
            color: datas[i].itemColor ? datas[i].itemColor : layers.randomColor(col, layers),
            borderWidth: 0
          };
        }
      } else {
        const col = i * level + level;
        // 先进行是否存在自定义颜色行为判断 开始
        if (layers.customSunburstColor.length) {
          datas[i].itemStyle = {
            color: layers.randomColor(col, layers),
            borderWidth: 0
          };
        } else {
          datas[i].itemStyle = {
            color: datas[i].itemColor ? datas[i].itemColor : layers.randomColor(col, layers),
            borderWidth: 0
          };
        }
      }
      if (layers.customSunburstLableColor) {
        datas[i].label = {
          color: layers.customSunburstLableColor
        };
      } else {
        datas[i].label = {
          color: datas[i].color ? datas[i].color : colorPicker.sunburst.color
        };
      }
      // 定义图例样式 开始
      this.graph.push({
        name: datas[i].name,
        color: datas[i].itemStyle.color
      });
      // 定义图例样式 结束
      // 先进行是否存在自定义颜色行为判断 结束
      if (datas[i].children && datas[i].children.length) {
        layers.calSunbrustData(datas[i].children, level, index, layers);
      }
    }
    return datas;
  }, // 自定义颜色时计算数据调用
  /**
   * 计算层级参数
   * @param {*} level 层级
   */
  calLevelStyle(level) {
    level = parseInt(level) + 1;
    const levelStyle = [{}];
    const width = parseInt(100 / level);
    for (let i = 1; i < level; i++) {
      if (i !== level) {
        levelStyle.push({
          r0: i * width + '%',
          r: (i + 1) * width + '%',
          itemStyle: {
            borderWidth: 1
          },
          label: {
            rotate: 'tangential'
          }
        });
      } else {
        levelStyle.push({
          r0: level * width + '%',
          r: (level + 1) * width + '%',
          itemStyle: {
            borderWidth: 1
          },
          label: {
            position: 'outside',
            padding: 3,
            silent: false
          }
        });
      }
    }
    return levelStyle;
  }, // 计算层级样式
  /**
   * 自由选取颜色 初始化
   * @param {*} i hash
   */
  randomColor(i) {
    // const r = Math.floor(Math.random() * 256);
    // const g = Math.floor(Math.random() * 256);
    // const b = Math.floor(Math.random() * 256);
    // return `rgb( ${r} , ${g},${b})`;
    // 判断是否存在自定义颜色行为 开始
    if (this.customSunburstColor.length) {
      const len = this.customSunburstColor.length;
      let key = this.curPosition % len;
      if (key < 1) {
        key = 1;
      }
      return this.customSunburstColor[key - 1];
    }
    // 判断是否存在自定义颜色行为 结束
    let key = this.curPosition % colorPicker.color.length;
    if (key < 1) {
      key = 1;
    }
    const color = colorPicker.color[key - 1];
    return color;
  }, // 随机颜色生成
  /**
   * 自由选取颜色 自定义颜色
   * @param {*} i hash
   */
  randomColorZ(i, layers) {
    // 判断是否存在自定义颜色行为 开始
    if (layers.customSunburstColor.length) {
      const len = layers.customSunburstColor.length;
      let key = this.curPosition % len;
      if (key < 1) {
        key = 1;
      }
      return layers.customSunburstColor[key - 1];
    }
    // 判断是否存在自定义颜色行为 结束
    let key = this.curPosition % colorPicker.color.length;
    if (key < 1) {
      key = 1;
    }
    const color = colorPicker.color[key - 1];
    return color;
  }, // 随机颜色生成
  /**
   * 创建地图饼图专题图
   */
  createLayer(map, data) {
    if (!map) {
      return;
    }
    if (!data || !data.data.length) {
      return;
    }
    this.activeMap = map;
    const sunbrustMarkers = this.createMarker(data.data); // 创建好所有marker
    const sunbrustLayer = L.layerGroup(sunbrustMarkers)
      .addTo(map);
    styleModify.onZoom(this.activeMap, sunbrustMarkers); // 为markers绘图添加缩放监听改变z-Index，marker的纬度会随着纬度变化而变化;
    // 此处必须先把容器加到地图上才能加载图表

    this.sunbrustLayer = sunbrustLayer;
    // 将容器加载到地图容器
    this.createCharts(sunbrustMarkers, data.data);
    // 自定义颜色开始
    sunbrustLayer.setCustomColor = this.setCustomColor;
    sunbrustLayer.setOpacity = styleModify.setOpaticty; // 设置图层透明度
    sunbrustLayer.setVisible = styleModify.setVisible; // 设置图层可见性
    sunbrustLayer.setZIndexOffset = this.setZIndexOffset; // 设置调整图层顺序函数;
    sunbrustLayer.customSunburstLableColor = this.customSunburstLableColor;
    sunbrustLayer.customSunburstColor = this.customSunburstColor;
    sunbrustLayer.calSunbrustData = this.calSunbrustDataZ;
    sunbrustLayer.randomColor = this.randomColorZ;
    sunbrustLayer.maxLevel = this.maxLevel;
    sunbrustLayer.charts = { ...this.charts
    };
    const layerId = "sunburst_chart_" + data.id + "_" + +new Date();
    // 设置容器初始ZINdex,为后面调整图层顺序功能 开始
    styleModify.setLayerOrder(styleModify.curZindex, sunbrustLayer._layers, layerId);
    styleModify.layerOrder[layerId] = styleModify.curZindex;
    styleModify.curZindex -= 1;
    // 设置容器初始ZINdex,为后面调整图层顺序功能 结束
    sunbrustLayer.layerId = layerId;
    sunbrustLayer.autoCalgraph = this.autoCalgraph;
    // 自定义颜色结束
    const sunbrustLayerInfo = {
      layerId,
      name: data.name,
      type: "sunburst",
      show: data.showThumbnails !== false,
      layer: sunbrustLayer,
      html: this.calgraph(layerId)
    };
    this.sunbrustLayerInfo = sunbrustLayerInfo;
    sgisLayerBase.setOverLayers(sunbrustLayerInfo);
    return sunbrustLayerInfo;
  },
  /**
   * 创建echarts容器
   */
  createMarker(datas) {
    const resultMarkers = [];
    for (let i = 0; i < datas.length; i++) {
      const time = +new Date();
      // 初始化最小宽高开始
      const data = datas[i];
      let width = colorPicker.size;
      if (data.hasOwnProperty('width')) {
        width = data.width.slice(0, -2);
        width = parseInt(width);
        if (width < colorPicker.size) {
          width = colorPicker.size;
        }
      }
      let height = colorPicker.size;
      if (data.hasOwnProperty('height')) {
        height = data.width.slice(0, -2);
        height = parseInt(height);
        if (height < colorPicker.size) {
          height = colorPicker.size;
        }
      }
      // 初始化最小宽高结束
      const chartMarker = L.marker([datas[i].lat, datas[i].lon], {
        id: "sunburst_chart_" + i + time, // 生成id
        pane: styleModify.pane, // 为设置自定义的图层顺序特别设定
        icon: L.divIcon({
          className: "",
          iconSize: [width, height],
          html: `
          <div id = "sunburst_chart_${i}${time}"
          style = "width:${width}px;height:${height}px;position:absolute;background-color:transparent;z-index='99998';" >
          </div>
          `
        })
      });
      resultMarkers.push(chartMarker);
    }
    return resultMarkers;
  },
  /**
   * 创建图表
   * @param {Object} sunbrustMarkers 图表容器
   * @param {Object} datas 数据
   */
  createCharts(sunbrustMarkers, datas) {
    const charts = [];
    for (let i = 0; i < datas.length; i++) {
      this.maxLevel[i] = 0;
      const chart = echarts.init(document.getElementById(sunbrustMarkers[i].options.id));
      this.graph = [];
      this.curPosition = 0;
      const seriesData = this.calSunbrustData(datas[i].data, 0, i);
      const chartOption = {
        tooltip: {
          show: true
        },
        series: {
          type: 'sunburst',
          highlightPolicy: 'ancestor',
          data: seriesData,
          radius: [0, '95%'],
          sort: null,
          levels: this.calLevelStyle(this.maxLevel[i])
        }
      };
      chart.setOption(chartOption);
      charts.push({
        id: sunbrustMarkers[i].options.id,
        echart: chart
      });
    }
    this.charts = charts;
  },
  /**
   * 设置自定义颜色函数setCustomColor
   * @param {object} par:{
   *  axisLabelStyle:'标签颜色',
   *  sunburstStyle:['颜色1','颜色2',....]
   * }
   */
  setCustomColor(layers, pars) {
    const par = {
      ...pars,
      sunburstStyle: pars.colors
    };
    // 设置标签颜色开始
    if (par.hasOwnProperty('axisLableStyle')) {
      layers.customSunburstLableColor = par.axisLableStyle;
    }
    // 设置标签颜色结束
    // 设置旭日图数据颜色开始
    if (par.hasOwnProperty('sunburstStyle')) {
      layers.customSunburstColor = par.sunburstStyle;
    }
    // 设置旭日图数据颜色结束
    for (const key in layers.charts) {
      const chart = layers.charts[key].echart;
      let option = chart.getOption();
      if (par.hasOwnProperty('sunburstStyle')) {
        const color = par.sunburstStyle;
        color.push(par.axisLableStyle);
        option.color = color;
      }
      const data = option.series;
      const oData = data[0];
      this.graph = [];
      this.curPosition = 0;
      const seriesData = layers.calSunbrustData(oData.data, 0, key, layers);
      const levels = data[0].levels;
      option = {
        ...option,
        series: {
          type: 'sunburst',
          highlightPolicy: 'ancestor',
          data: seriesData,
          radius: [0, '95%'],
          sort: null,
          levels
        }
      };
      layers.charts[key].echart.clear();
      layers.charts[key].echart.setOption(option);
      this.autoCalgraph(layers.layerId);
    }
  },
  // 图例计算颜色 开始
  /**
   * 图例样式html代码注入
   * @param {*} layerId 图层id
   */
  calgraph(layerId) {
    let html = `<div style="padding:10px" class="${layerId}">`;
    for (const key in this.graph) {
      html += `<div style='transform:translateX(-30px)'>
        <div style = 'display:inline-block;width:0px;height:0px;margin:0;padding:0;border-radius:20px;border:20px solid transparent;border-right-color:${this.graph[key].color};'> 
          <div style = 'width:0px;height:0px;margin:0;padding:0;border-radius:14px;border:14px solid transparent;border-right-color:#F5F5F5;transform:translate(-16px,-15px)'>
          </div>
        </div>
        <div style = 'display:inline-block;;margin:0;padding:0;padding-left:5px;line-height:30px;transform:translateY(-16px)'>${this.graph[key].name}</div>
      </div>`;
    }
    html += '</div>';
    return html;
  },
  /**
   * 自定义颜色时图例样式html代码注入
   * @param {*} layerId 图层id
   */
  autoCalgraph(layerId) {
    let html = `<div style="padding:10px" class="${layerId}">`;
    for (const key in this.graph) {
      html += `<div style='transform:translateX(-30px)'>
        <div style = 'display:inline-block;width:0px;height:0px;margin:0;padding:0;border-radius:20px;border:20px solid transparent;border-right-color:${this.graph[key].color};'> 
          <div style = 'width:0px;height:0px;margin:0;padding:0;border-radius:14px;border:14px solid transparent;border-right-color:#F5F5F5;transform:translate(-16px,-15px)'>
          </div>
        </div>
        <div style = 'display:inline-block;;margin:0;padding:0;padding-left:5px;line-height:30px;transform:translateY(-16px)'>${this.graph[key].name}</div>
      </div>`;
    }
    html += '</div>';
    const layers = sgisLayerBase.overLayers;
    for (const key in layers) {
      if (layers[key].layerId === layerId) {
        layers[key].html = html;
      }
    }
    // sgisLayerBase.layerControlChange();
  },
  // 图例计算颜色 结束
  /** 设置调整图层顺序函数*/
  setZIndexOffset(index) {
    styleModify.setZIndexOffset(index, this.layerId, this._layers);
  }
};
